package com.designoutput.service
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	public class BaseHttpService extends EventDispatcher
	{
		private var _result:Object;
		public var loader:URLLoader;
		public var request:URLRequest;

		public function BaseHttpService(url:String=null)
		{
			request=new URLRequest(url);
			request.method=URLRequestMethod.POST;
			loader=new URLLoader(request);
			loader.dataFormat=URLLoaderDataFormat.TEXT;
			loader.addEventListener(Event.COMPLETE, resultHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
		}

		public function get result():Object
		{
			return _result;
		}

		public function send(parameters:Object=null):void
		{
			var info:String="request " + request.url + ": ";
			var data:URLVariables=new URLVariables();
			for (var key:String in parameters)
			{
				data[key]=parameters[key];
				info+=key + "=" + parameters[key] + ";";
			}
			request.data=data;
			loader.load(request);
			trace("send", info);
		}

		public function resend():void
		{
			loader.load(request);
		}

		private function resultHandler(evt:Event):void
		{
			this._result = loader.data;
			this.dispatchEvent(new Event(Event.COMPLETE));
		}

		private function errorHandler(evt:Event):void
		{
			trace("com.designoutput.service.HttpService::errorHandler");
			this.dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, ErrorEvent(evt).text));
		}
	}
}